import 'dart:async';
import 'dart:convert';
import 'package:byw_blog/utils/ConfigUtil.dart';
import 'package:http/http.dart' as http;

class Network {
  // get请求的封装，传入的两个参数分别是请求URL和请求参数，请求参数以map的形式传入，会在方法体中自动拼接到URL后面
  /// 请求方式有两种传参方式
  /// 1、type为TYPE_PATH_PARAMS，使用listParams参数，请求的链接格式为 http://xxx/api/{name}
  /// 2、type为TYPE_KEY_PARAMS，使用mapParams参数，请求的链接格式为 http://xxx/api?name=123
  static Future<String> get(String url,
      {List<String>? listParams, Map<String, dynamic>? keyParams}) async {
    if (listParams != null) {
      url = url.substring(0, url.lastIndexOf("/"));
      for (var value in listParams!) {
        url += "/$value";
      }
    }
    var api = await ConfigUtil.getInterfaceAddress();
    var uri = Uri.http(api, url, keyParams);
    http.Response res = await http.get(uri);
    var result = json.decode(res.body);
    if (result["statusCode"] == 200) {
      return json.encode(result['data']);
    } else {
      throw Exception("请求错误，响应码：${result["statusCode"]}");
    }
  }

  // post请求
  static Future<dynamic> post(String url, {Map<String, String>? params}) async {
    var api = await ConfigUtil.getInterfaceAddress();
    http.Response res =
        await http.post(Uri(host: api, path: url), body: params);
    var result = json.decode(res.body);
    if (result["statusCode"] == 200) {
      return result['data'];
    } else {
      throw Exception("请求错误，响应码：${result["statusCode"]}");
    }
  }

  // get请求的封装，传入的两个参数分别是请求URL和请求参数，请求参数以map的形式传入，会在方法体中自动拼接到URL后面
  /// 请求方式有两种传参方式
  /// 1、type为TYPE_PATH_PARAMS，使用listParams参数，请求的链接格式为 http://xxx/api/{name}
  /// 2、type为TYPE_KEY_PARAMS，使用mapParams参数，请求的链接格式为 http://xxx/api?name=123
  /// 注意：这里的接口用的是本地接口
  static Future<dynamic> getLocalInterface(String url,
      {List<String>? listParams, Map<String, dynamic>? keyParams}) async {
    if (listParams != null) {
      url = url.substring(0, url.lastIndexOf("/"));
      for (var value in listParams!) {
        url += "/$value";
      }
    }
    var uri = Uri.http("192.168.0.131:8080",
        "/byw_blog_backstage_war_exploded/$url", keyParams);
    http.Response res;
    try {
      res = await http.get(uri);
    } catch (e) {
      throw Exception("请求错误，原因：$e");
    }
    return res.body;
  }
}
